package Thread.PC;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}10:39
 */
class Data{
    AtomicInteger sum = new AtomicInteger();
    Lock lock = new ReentrantLock();
    Condition A = lock.newCondition();
    Condition B = lock.newCondition();
    Condition C = lock.newCondition();
    int flag = 0;

     void ATest(){
        lock.lock();
        try {
            while (flag != 0){
                A.await();
            }
            for (int i = 0; i < 5; i++){
                sum.incrementAndGet();
                System.out.println(Thread.currentThread().getName()+"\t"+sum);
            }
            flag = 1;
            B.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

     void BTest(){
        lock.lock();
        try {
            while (flag != 1){
                B.await();
            }
            for (int i = 0; i < 5; i++){
                sum.incrementAndGet();
                System.out.println(Thread.currentThread().getName()+"\t"+sum);
            }
            flag = 2;
            C.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

     void CTest(){
        lock.lock();
        try {
            while (flag != 2){
                C.await();
            }
            for (int i = 0; i < 5; i++){
                sum.incrementAndGet();
                System.out.println(Thread.currentThread().getName()+"\t"+sum);
            }
            flag = 0;
            A.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
public class ConditionDemo {


    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            data.ATest();
        },"A").start();
        new Thread(() -> {
            data.BTest();
        },"B").start();
        new Thread(() -> {
            data.CTest();
        },"C").start();
    }
}
